package com.example.springboot.controller.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/7/13 21:38
 */
@Component
@ServerEndpoint("/webSocket/{uid}")
public class XunWebsocketServer {
    // 计数
    private static final AtomicInteger onlineNum = new AtomicInteger(0);
    //
    private static CopyOnWriteArraySet<Session> sessionPools = new CopyOnWriteArraySet<>();

    @OnOpen
    public void open(Session session, @PathParam("uid") String uid) {
        // 加入连接池
        sessionPools.add(session);
        onlineNum.incrementAndGet();
        //
        System.out.println("欢迎" + uid + "加入此时有" + onlineNum.get() + "个连接");
    }

    @OnClose
    public void close(Session session) {
        sessionPools.remove(session);
        onlineNum.decrementAndGet();
        System.out.println(session.getId()+"离开，现在有"+onlineNum.get()+"个连接");
    }

    public void sendMessage(Session session,String message) throws IOException {
        if (session!=null){
            synchronized (session){
                session.getBasicRemote().sendText(message);
            }
        }
    }


    public void sendMessageGroup(String message) throws IOException {
        for (Session session : sessionPools) {
            if (session.isOpen()){
                sendMessage(session,message);
            }
        }
    }
    
}
